package com.example.com.daervideo.vm;


import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.databinding.ObservableBoolean;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.example.com.daervideo.activitys.loginRegist.RegistActivity;
import com.example.com.daervideo.databinding.ActivityRegistBinding;
import com.example.com.daervideo.entity.BaseListEntity;
import com.example.com.daervideo.entity.InviteQQWeChat;
import com.example.com.daervideo.initerface.ApiService;
import com.example.com.daervideo.utils.DESUtils;
import com.example.com.daervideo.utils.MD5Utils;
import com.example.com.daervideo.utils.RetrofitClient;

import java.lang.ref.WeakReference;
import java.util.logging.LogRecord;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Created by i7-1 on 2018/11/23.
 */

public class RegistViewModel extends BaseViewModel {

    private final ActivityRegistBinding binding;
    private final RegistViewModel that;

    public ObservableBoolean showInvit = new ObservableBoolean(false);
    private final ApiService apiService;
    private int time = 60;
    private final MainHandler handler;


    public RegistViewModel(RegistActivity registActivity) {
        super(registActivity);
        binding = registActivity.getBinding();
        that = this;
        apiService = RetrofitClient.getInstance().create(ApiService.class);
        handler = new MainHandler(registActivity);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        apiService.getQQAndWeChat().compose(RxUtils.bindToLifecycle(context)) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                })
                .subscribe(new Consumer<BaseResponse<InviteQQWeChat>>() {
                    @Override
                    public void accept(BaseResponse<InviteQQWeChat> response) throws Exception {
                        dismissDialog();
                        if (response.getCode() == 0) {
                            String qqGroupId = response.getData().getQqGroupId();
                            String weChat = response.getData().getWeChat();
                            binding.weichat.setText("火鸟视频微信号\n" + weChat);
                            binding.qq.setText("火鸟视频QQ群\n" + qqGroupId);
                        } else {
                        }

                    }
                }, new Consumer<ResponseThrowable>() {
                    @Override
                    public void accept(ResponseThrowable throwable) throws Exception {
                        dismissDialog();
                    }
                });
    }

    public BindingCommand getCode = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            String phone = binding.phone.getText().toString().trim();
            if (StringUtils.isEmpty(phone) && phone.length() != 11) {
                ToastUtils.showShort("手机号码有误");
                return;
            }
            binding.buttonCode.setClickable(false);
            apiService.getRegistCode(phone)
                    .compose(RxUtils.bindToLifecycle(context)) //请求与View周期同步
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog();
                        }
                    })
                    .subscribe(new Consumer<BaseResponse<BaseListEntity>>() {
                        @Override
                        public void accept(BaseResponse<BaseListEntity> response) throws Exception {
                            dismissDialog();
                            if (response.getCode() == 0) {
                                Message message = handler.obtainMessage(1);     // Message
                                handler.sendMessageDelayed(message, 1000);
                            } else {
                                ToastUtils.showShort(response.getMsg());

                                binding.buttonCode.setClickable(true);
                            }

                        }
                    }, new Consumer<ResponseThrowable>() {
                        @Override
                        public void accept(ResponseThrowable throwable) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(throwable.message);
                            throwable.printStackTrace();

                            binding.buttonCode.setClickable(true);
                        }
                    });

        }
    });

    public BindingCommand regist = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            String phone = binding.phone.getText().toString().trim();

            String firtPassword = binding.inputPassword.passwordEditText.getText().toString().trim();

            String secondPassword = binding.performPassword.passwordEditText.getText().toString().trim();
            String code = binding.code.getText().toString().trim();
            String inviteCode = binding.inviteCode.getText().toString().trim();

            if (StringUtils.isEmpty(code) || StringUtils.isEmpty(phone) || StringUtils.isEmpty(firtPassword) || StringUtils.isEmpty(secondPassword) || !firtPassword.equals(secondPassword)) {
                ToastUtils.showShort("填写有误！");
                return;
            }
            String md5Password = DESUtils.utilEncode(firtPassword);
            apiService.userRegesit(phone, md5Password, code, inviteCode, null)
                    .compose(RxUtils.bindToLifecycle(context)) //请求与View周期同步
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog();
                        }
                    })
                    .subscribe(new Consumer<BaseResponse<BaseListEntity>>() {
                        @Override
                        public void accept(BaseResponse<BaseListEntity> response) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(response.getMsg());
                            if (response.getCode() == 0) {
                                AppManager.getAppManager().finishActivity();
                            } else {
                                ToastUtils.showShort(response.getMsg());
                            }

                        }
                    }, new Consumer<ResponseThrowable>() {
                        @Override
                        public void accept(ResponseThrowable throwable) throws Exception {
                            dismissDialog();
                            ToastUtils.showShort(throwable.message);
                            throwable.printStackTrace();
                        }
                    });

        }
    });

    public BindingCommand copyQQ = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            String s = binding.qq.getText().toString();
            String[] split = s.split("\n");
            if (split.length == 2) {
                ClipData clipData = ClipData.newPlainText("qq", split[1]);
                cm.setPrimaryClip(clipData);
                ToastUtils.showShort("成功");
            }
        }
    });
    public BindingCommand copyWeiChat = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            String s = binding.weichat.getText().toString();
            String[] split = s.split("\n");
            if (split.length == 2) {
                ClipData clipData = ClipData.newPlainText("weichat", split[1]);
                cm.setPrimaryClip(clipData);
                ToastUtils.showShort("成功");
            }

        }
    });
    public BindingCommand getInvitCode = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            that.showInvit.set(true);
        }
    });


    @Override
    public void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();

    }

    private class MainHandler extends Handler {
        private final WeakReference<Activity> reference;

        public MainHandler(RegistActivity activity) {
            reference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Activity activity = reference.get();
            if (activity != null) {
                time--;
                binding.buttonCode.setText(time + "s");
                if (time > 0) {
                    Message message = handler.obtainMessage(1);
                    handler.sendMessageDelayed(message, 1000);      // send message
                } else {

                    binding.buttonCode.setClickable(true);
                    binding.buttonCode.setText("获取验证码");
                    time = 60;
                }
            }
            super.handleMessage(msg);
        }
    }
}
